import pymysql

# 数据库的帮助手册
class MysqlHelper():
    def __init__(self,host , user , password , database , port=3306 , charset="utf8"):
        self.host=host
        self.user=user
        self.password=password
        self.database=database
        self.port=port
        self.charset=charset

    def connect(self):
        self.connection=pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database,
            port=self.port,
            charset=self.charset
        )
        self.cursor=self.connection.cursor()

    def close(self):
        self.cursor.close()
        self.connection.close()

    def insert(self,sql,params=[]):
        count=None
        try:
            self.connect()  # 连接
            count=self.cursor.execute(sql,params)  # 执行
            self.connection.commit()  # 提交
            self.close()  # 关闭
        except Exception as e:
            print(e)
        return count

    def fetch_one(self,sql,params=[]):
        count = None
        try:
            self.connect()  # 连接
            self.cursor.execute(sql, params)  # 执行
            count = self.cursor.fetchone()  # 获取一条记录
            self.close()  # 关闭
        except Exception as e:
            print(e)
        return count

# 用户执行 注册和登录 功能
class Person():
    # 注册
    def register(self):
        name=input("请输入用户名:")
        password=input("请输入密码:")
        # 点击注册按钮，将数据插入数据库中
        helper=MysqlHelper(host="localhost",user="root",password="1234",database="hqyj")
        count = helper.insert("insert into tb_users(username,password) values(%s,%s)",[name,password])
        # 检查是否注册成功
        if count>0:
            print("注册成功")
        else:
            print("注册失败,请重新注册")

    def login(self):
        name=input("请输入用户名:")
        password=input("请输入密码:")
        # 点击登录按钮，从数据库中获取数据
        helper = MysqlHelper(host="localhost", user="root", password="1234", database="hqyj")
        count = helper.fetch_one("select count(*) from tb_users where username=%s and password=%s",
                              [name, password])
        # 检查是否登录成功
        if count[0]>0:
            print("登录成功")
        else:
            print("登录失败,请重新登录")

if __name__ == '__main__':
    while True:
        print("1.淘宝注册")
        print("2.淘宝登录")
        print("3.退出")
        choice = input("请输入你的选择:")
        user = Person()
        if choice == "1":
            user.register()
        elif choice == "2":
            user.login()
        elif choice == "3":
            break
        else:
            print("输入错误，请重新输入")



